package com.rpp.utils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Description 自定义类加载器
 * @Author peng
 * @Date 2020/7/23 10:24 上午
 */
public class MyClassLoader extends ClassLoader {

    /**
     * 指定class文件根目录
     */
    private String location;

    public MyClassLoader(String location) {
        this.location = location;
    }

    /**
     * 类的文件名  com.rpp.servlet.MyServlet1
     */
    @Override
    public Class<?> findClass(String name) {
        byte[] datas = loadClassData(name);
        return defineClass(name, datas, 0, datas.length);
    }

    protected byte[] loadClassData(String name) {
        FileInputStream fis = null;
        byte[] datas = null;
        try {
            String path = name.replace(".", "/");
            fis = new FileInputStream(location + path + ".class");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int b;
            while ((b = fis.read()) != -1) {
                bos.write(b);
            }
            datas = bos.toByteArray();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return datas;

    }
}
